(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.popup.documentCreateController', controller);
	controller.$inject = [ '$scope', '$q', '$uibModalInstance', 'Constants', 'dialogsModule', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig',
			'authService', 'documentService' ];
	function controller($scope, $q, $uibModalInstance, Constants, dialogsModule, gridService, modalService, layoutConfig, validatorConfig, authService, documentService) {
		var ctrl = this, params = $scope.$stateParams.params, log = $scope.loggerFactory.getLogger("documentPopup"), dialogParams;
		ctrl.dialogsModule = dialogsModule;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		dialogParams = dialogsModule.params;
		ctrl.formName = 'documentCreatePopupForm';
		ctrl.ok = function() {
			if($scope.documentCreatePopupForm) {
				$scope.documentCreatePopupForm.$setSubmitted();
				if(!$scope.documentCreatePopupForm.$valid) {
					dialogsModule.showErrorMessages($scope.documentCreatePopupForm);
					return;
				}
			}
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['ok'] || dialogsModule.btnCallback['ok'](ctrl.document) !== false) {
				$uibModalInstance.close();
			}
		};
		
		ctrl.close = function() {
			if (!dialogsModule.btnCallback || !dialogsModule.btnCallback['close'] || dialogsModule.btnCallback['close']() !== false) {
				$uibModalInstance.dismiss();
			}
		};
		
		ctrl.init = function() {
			ctrl.create();
		};
		ctrl.create = function() {
			ctrl.document = {};
			authService.createAttachment(params).then(function(response) {
				ctrl.document = response.data || params;
				documentService.initDropDownDataOptions(ctrl).then(function() {
				});
			});
		};
		var watcher = $scope.$watch('vm.document.uploadObj[0]', function(modelValue, oldValue, scope) {
			var obj = ctrl.document || {};
			if(modelValue) {
				obj.docId = modelValue.docId;
				obj.docTitle = obj.docTitle || modelValue.docFileName.substring(0, modelValue.docFileName.lastIndexOf("."));
				obj.docMimeType = modelValue.docMimeType;
				obj.serviceCode = modelValue.serviceCode;
			} else {
				obj.docId = '';
				obj.docTitle = '';
				obj.docMimeType = '';
				obj.serviceCode = '';
			}
		});
		$scope.$on('$destroy', function() {
			(watcher || angular.noop)();
		});
	}
})(angular);